Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime

<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase

    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    ' The execution engine calls this method when the task executes.
    ' To access the object model, use the Dts property. Connections, variables, events,
    ' and logging features are available as members of the Dts property as shown in the following examples.
    '
    ' To reference a variable, call Dts.Variables("MyCaseSensitiveVariableName").Value
    ' To post a log entry, call Dts.Log("This is my log text", 999, Nothing)
    ' To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, True)
    '
    ' To use the connections collection use something like the following:
    ' ConnectionManager cm = Dts.Connections.Add("OLEDB")
    ' cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;"
    '
    ' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
    ' 
    ' To open Help, press F1.



    Public Sub Main()

        Dim sOrderFile As String = Dts.Variables("strOrderFilePath").Value

        Dim lines As String()

        Dim bIsError As Boolean = False

        Dim sErrorMessage As String = ""

        If Not System.IO.File.Exists(sOrderFile) Then

            MsgBox("Navigating file does not exist or file path is not valid!", MsgBoxStyle.Exclamation)

        Else

            lines = System.IO.File.ReadAllLines(sOrderFile)

            If lines.GetUpperBound(0) < 3 Then

                MsgBox("Navigating file does not have all parameters needed. 1.File Name 2.Delimeter 3.Columns numbers or All! 4.Yes or No for a header row!")

            Else

                Dim sfileName As String = lines(0)

                Dim sDelimeter As Char() = {lines(1)(0)}

                Dim sColumns As String = lines(2)

                Dim sHeader As String = lines(3)

                Dim iColumn As Integer = 0



                Dim columns As String()

                Dim i As Integer = 0

                Dim y As Integer = 0

                Dim sbOutput As New System.Text.StringBuilder()

                Dim iStart As Integer = 0

                If Not System.IO.File.Exists(sfileName) Then

                    bIsError = True

                    MsgBox("Input file does not exist or file path is not valid. Please fix file path and rerun the package!", MsgBoxStyle.Exclamation)

                ElseIf sHeader.ToUpper <> "NO" And sHeader.ToUpper <> "YES" Then

                    bIsError = True

                    MsgBox("If the first row in the Input File has column names enter Yes on Line 4, and No if no column names.", MsgBoxStyle.Exclamation)

                Else

                    If sDelimeter(0).ToString() <> ";" And sDelimeter(0).ToString() <> ":" And sDelimeter(0).ToString() <> "," And sDelimeter(0).ToString() <> "t" And sDelimeter(0).ToString() <> "|" Then

                        bIsError = True

                        sErrorMessage = "The provided delimiter is not supported by this package. Please review the list of supported delimiters - Semicolon {;}, Colon {:}, Comma {,}, Tab {t}, Vertical bar {|}"

                    End If

                    If sDelimeter(0).ToString() = "t" Then

                        sDelimeter(0) = vbTab

                    End If

                    Dim lines1 As String() = System.IO.File.ReadAllLines(sfileName)

                    If sColumns.ToUpper = "ALL" Then

                        Dim sbHeader As New System.Text.StringBuilder()

                        Dim cnt As Integer = 0

                        For Each item In lines1(0).Split(sDelimeter)

                            sbHeader.Append(cnt.ToString() + ",")

                            cnt = cnt + 1

                        Next

                        sColumns = sbHeader.ToString()

                        sColumns = sColumns.Remove(sColumns.Length - 1)

                    End If

                    For Each sColumn In sColumns.Split(",")

                        y = 0

                        For Each line1 As String In lines1

                            If Not bIsError Then

                                If sHeader.ToUpper = "YES" And iStart = 0 Then

                                    'DO NOTHING

                                    iStart = iStart + 1

                                Else

                                    columns = line1.Split(sDelimeter)

                                    If IsNumeric(sColumn) Then

                                        iColumn = Convert.ToInt16(sColumn)

                                        If iColumn > columns.GetUpperBound(0) Then

                                            bIsError = True

                                            sErrorMessage = "Wronge delimeter or provided column number does not exist in the input file. Please fix line two or three in the Order.txt file and rerun the package"

                                        Else

                                            i = columns(iColumn).Length

                                            If i > y Then

                                                y = i

                                            End If

                                        End If

                                        iStart = iStart + 1

                                    Else

                                        bIsError = True

                                        sErrorMessage = "Line 4 in the Order.txt file should have column numbers of your choice delimited by comma or word All, in case you want to scan all columns. Please check and fix"

                                    End If 'If IsNumeric(sColumn) Then

                                End If

                            End If

                        Next ' Each line1 As String In lines1

                        sbOutput.AppendLine(iColumn.ToString() & " - " & y.ToString())

                    Next 'Each sColumn In sColumns.Split(",")

                    If bIsError Then

                        MsgBox(sErrorMessage)

                    Else

                        writeOutputFile(sfileName, sbOutput.ToString())

                    End If

                End If ' If Not System.IO.File.Exists(sfileName) Then

            End If 'If lines.GetUpperBound(0) < 3 Then

        End If ' If Not System.IO.File.Exists(sOrderFile) Then

    End Sub

    Public Sub writeOutputFile(ByVal sfileName As String, ByVal message As String)

        Dim snewFileName As String = sfileName.Replace(sfileName.Substring(sfileName.IndexOf(".", 1)), "_BluePrint_" & Replace(Replace(Now.ToString(), "/", "_"), ":", "-") & sfileName.Substring(sfileName.IndexOf(".", 1)))

        If System.IO.File.Exists(snewFileName) Then

            System.IO.File.Delete(snewFileName)

        End If

        Using sw As System.IO.StreamWriter = System.IO.File.CreateText(snewFileName)

            sw.Write(message)

        End Using

    End Sub
End Class